<template>
  
  <div class="page-index">
    <div class="content">
      <img class="logo" src="@/assets/logo.png" />
      <div class="title">{{ title }}</div>
      <button class="download-btn" @click="getUrl">立即下载</button>
    </div>
    <div class="wxtip" v-if="isWeixin">
      <img class="wxtip-icon" src="@/assets/tip.png" alt="微信提示" />
      <div class="wxtip-txt">请点击右上角选择在浏览器中打开 或用浏览器/数字社科app扫码</div>
    </div>
  </div>
</template>
<script>
// import { getSn, Verificationcode } from "@/api/index.js";
import { getSn } from "@/api/index.js";
import CryptoJS from "crypto-js";
import { Base64 } from "js-base64";

export default {
  data() {
    return {
      title: "社科通",
      isWeixin: false,
      loading: false,
      key: "",
      iv: "",
      ioskey: [
        49, 113, 97, 122, 64, 87, 83, 88, 41, 79, 75, 77, 57, 105, 106, 110,
      ],
      iosiv: [
        122, 120, 99, 118, 47, 46, 44, 109, 94, 84, 70, 67, 55, 121, 103, 118,
      ],
      decryptedData: "",
      error: "",
      isDecrypting: false,
      cryptoMethod: "检测中...", // 记录使用的解密方式
      decrypted: "",
      snData: "",
    };
  },
  mounted() {
    this.checkWeixin();
    // 定义函数，返回计算后的 key 和 iv
    function getByteArr(ioskey, iosiv) {
      return {
        key: String.fromCharCode(...ioskey),
        iv: String.fromCharCode(...iosiv),
      };
    }
    // 调用并存储到 Vue 实例
    const byteArr = getByteArr(this.ioskey, this.iosiv);
    this.key = byteArr.key;
    this.iv = byteArr.iv;
    console.log(this.key, this.iv, 123456);
    // if (this.checkIOS) {
    //   this.getUrl();
    // }
  },
  methods: {
    checkWeixin() {
      const ua = navigator.userAgent.toLowerCase();
      this.isWeixin = /micromessenger/i.test(ua); // 检测是否包含 "micromessenger"
      console.log("Is WeChat:", this.isWeixin); // 调试用
    },
    async decryptData() {
      this.error = "";
      this.decryptedData = "";
      this.isDecrypting = true;

      try {
        // 验证输入
        if (!this.encryptedData.trim()) {
          throw new Error("请输入加密数据");
        }
        if (!this.key.trim()) {
          throw new Error("请输入密钥");
        }
        if (!this.iv.trim()) {
          throw new Error("请输入偏移量(IV)");
        }
        // 执行解密
        const result = await this.aesDecrypt(
          this.encryptedData.trim(),
          this.key.trim(),
          this.iv.trim()
        );
        this.decryptedData = result;
      } catch (err) {
        console.error("解密失败:", err);
        this.error = `解密失败: ${err.message}`;
      } finally {
        this.isDecrypting = false;
      }
    },
    /**
     * AES-CBC 解密（自动选择最佳方案）
     */
    async aesDecrypt(encryptedHex, key, iv) {
      // 优先尝试Web Crypto API
      if (this.checkCryptoSupport()) {
        try {
          this.cryptoMethod = "Web Crypto API";
          return await this.decryptWithWebCrypto(encryptedHex, key, iv);
        } catch (webCryptoError) {
          console.warn("Web Crypto API解密失败，尝试crypto-js", webCryptoError);
          // 继续尝试crypto-js
        }
      }
      // 使用crypto-js作为后备方案
      try {
        this.cryptoMethod = "crypto-js (兼容模式)";
        return this.decryptWithCryptoJS(encryptedHex, key, iv);
      } catch (error) {
        throw new Error(`所有解密方式均失败: ${error.message}`);
      }
    },

    /**
     * 使用Web Crypto API解密
     */
    async decryptWithWebCrypto(encryptedHex, key, iv) {
      try {
        // 将十六进制字符串转换为Uint8Array
        const encryptedBytes = this.hexToBytes(encryptedHex);

        // 将密钥和偏移量转换为Uint8Array
        const keyBytes = this.stringToBytes(key);
        const ivBytes = this.stringToBytes(iv);

        // 导入密钥
        const cryptoKey = await window.crypto.subtle.importKey(
          "raw",
          keyBytes,
          { name: "AES-CBC" },
          false,
          ["decrypt"]
        );

        // 解密
        const decryptedBuffer = await window.crypto.subtle.decrypt(
          {
            name: "AES-CBC",
            iv: ivBytes,
          },
          cryptoKey,
          encryptedBytes
        );

        // 转换为字符串
        return this.bytesToString(new Uint8Array(decryptedBuffer));
      } catch (error) {
        throw new Error(`Web Crypto API解密失败: ${error.message}`);
      }
    },

    /**
     * 使用crypto-js解密
     */
    decryptWithCryptoJS(encryptedHex, key, iv) {
      try {
        // 准备密钥和IV
        const keyHex = CryptoJS.enc.Utf8.parse(key);
        const ivHex = CryptoJS.enc.Utf8.parse(iv);

        // 将十六进制字符串转换为CryptoJS格式
        const encryptedHexStr = encryptedHex.toString();
        const encryptedBytes = CryptoJS.enc.Hex.parse(encryptedHexStr);

        // 执行解密
        const decrypted = CryptoJS.AES.decrypt(
          { ciphertext: encryptedBytes },
          keyHex,
          {
            iv: ivHex,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7,
          }
        );

        // 返回UTF-8字符串
        const result = decrypted.toString(CryptoJS.enc.Utf8);

        if (!result) {
          throw new Error("解密结果为空，可能是密钥或IV错误");
        }

        return result;
      } catch (error) {
        throw new Error(`crypto-js解密失败: ${error.message}`);
      }
    },

    /**
     * 检查浏览器是否支持Web Crypto API
     */
    checkCryptoSupport() {
      return (
        window.crypto &&
        window.crypto.subtle &&
        typeof window.crypto.subtle.importKey === "function"
      );
    },

    /**
     * 十六进制字符串转字节数组
     */
    hexToBytes(hex) {
      if (!hex) return new Uint8Array(0);
      if (hex.length % 2 !== 0) {
        throw new Error("十六进制字符串长度必须为偶数");
      }

      const bytes = new Uint8Array(hex.length / 2);
      for (let i = 0; i < hex.length; i += 2) {
        bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
      }
      return bytes;
    },

    /**
     * 字符串转字节数组（UTF-8编码）
     */
    stringToBytes(str) {
      return new TextEncoder().encode(str);
    },

    /**
     * 字节数组转字符串（UTF-8编码）
     */
    bytesToString(bytes) {
      console.log(new TextDecoder().decode(bytes), 1111);

      return new TextDecoder().decode(bytes);
    },
    checkIOS() {
      const ua = navigator.userAgent.toLowerCase();
      return ua.includes("iphone") || ua.includes("ipad");
    },
    // 检查是否为Android设备
    checkIsAndroid() {
      return (
        /android/i.test(navigator.userAgent) ||
        /qqbrowser/i.test(navigator.userAgent)
      );
    },
    // 检查是否为鸿蒙系统并获取版本
    // 检查是否为鸿蒙系统并获取版本
    checkHarmonyOS() {
      const ua = navigator.userAgent.toLowerCase();
      const isHuaweiDevice = /huawei|honor/i.test(ua);

      // 1. UA 检测（兼容 HarmonyOS、HMOS、OpenHarmony）
      const harmonyUAMatch = ua.match(
        /(harmonyos|hmos|openharmony)[\/\s]?([\d._]+)?/i
      );

      // 2. 全局对象检测
      const hasHarmonyBridge = typeof window.HarmonyBridge !== "undefined";
      const hasOHOSGlobal = typeof window.ohos !== "undefined";
      const hasOpenHarmonyAPI = "openHarmony" in window;

      // 3. 文件系统/Intent API 检测
      const hasHarmonyFS = "ohosFileSystem" in window;
      const hasHarmonyIntent = "ohosIntent" in window;

      // 4. WebView 检测（HWBrowser、OpenHarmony WebView）
      const isHarmonyWebView =
        /(hwbrowser|ohwebview)\/[\d.]+/i.test(ua) &&
        /(harmony|openharmony)/i.test(ua);

      // 综合判断
      const isHarmony =
        harmonyUAMatch ||
        hasHarmonyBridge ||
        hasOHOSGlobal ||
        hasOpenHarmonyAPI ||
        hasHarmonyFS ||
        hasHarmonyIntent ||
        (isHuaweiDevice && isHarmonyWebView);
      // 版本号提取
      let version = "unknown";
      if (harmonyUAMatch?.[2]) {
        version = harmonyUAMatch[2].replace(/_/g, ".");
      } else if (hasOHOSGlobal) {
        version = window.ohos?.version || getOpenHarmonyVersion();
      } else if (hasHarmonyBridge) {
        version = "2.0"; // 默认最低版本
      }
      return {
        isHarmony: !!isHarmony,
        version: version,
      };
    },
    // 处理URL获取逻辑
    async getUrl() {
      try {
        const isIOS = this.checkIOS();
        const isAndroid = this.checkIsAndroid();
        const harmonyInfo = this.checkHarmonyOS();
        if (isIOS) {
          await this.handleIOSFlow();
        } else if (isAndroid) {
          this.handleAndroidDownload();
        } else if (harmonyInfo.isHarmony) {
          // alert(harmonyInfo.isHarmony);
          // 鸿蒙系统处理逻辑

          //  alert(harmonyInfo.version);
          if (harmonyInfo.version > 4.2) {
            // 鸿蒙4.2及以上版本

            this.handleAndroidDownload();
          } else {
            // 鸿蒙4.2以下版本

            this.handleAndroidDownload();
          }
          // this.handleAndroidDownload();
        } else {
          this.handleAndroidDownload();
          console.log("请在iOS、Android或HarmonyOS设备上打开此页面");
          // alert("暂不支持，请降低版本");
          return;
        }
      } catch (err) {
        console.error("处理URL时出错:", err);
        // 可以在这里添加错误处理逻辑，如显示错误提示等
      }
    },
    // 显示不支持提示
    showUnsupportedMessage() {
      // alert("正在建设中，目前暂不支持。");
    },
    // 处理iOS流程
    async handleIOSFlow() {
      // 原有代码保持不变
      // 1. 获取接口数据
      const response = await getSn();
      console.log("完整响应:", response);

      // 2. 检查数据结构
      if (!response.data) {
        throw new Error("接口未返回有效数据");
      }

      // 3. 存储并处理数据
      this.snData = response.data;
      console.log("待解密数据:", this.snData);
      console.log("Key:", this.key, "IV:", this.iv);

      // 4. 执行解密
      const decrypted = await this.aesDecrypt(this.snData, this.key, this.iv);
      const plainText = Base64.decode(decrypted.trim());
      this.decryptedData = JSON.parse(plainText);

      // 5. 跳转URL
      window.location.href = this.decryptedData.data.url;
    },
    // 处理Android下载
    handleAndroidDownload() {
      const url = "http://szsky.cass.cn:9527/download/szsk_4.1.5.apk";
      const fileName = "szsk_4.1.5.apk";

      // 检测QQ浏览器
      const isQQBrowser =
        navigator.userAgent.toLowerCase().indexOf("qqbrowser") > -1;

      // 对于QQ浏览器，直接使用window.location.href
      if (isQQBrowser) {
        window.location.href = url;
        return;
      }

      // 方法1：使用 <a download>（现代浏览器）
      if ("download" in document.createElement("a")) {
        const link = document.createElement("a");
        link.href = url;
        link.download = fileName;
        link.style.display = "none";
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          document.body.removeChild(link);
        }, 100);
      }
      // 方法2：使用 window.open（兼容旧浏览器）
      else {
        window.open(url, "_blank");
      }

      // 方法3：如果前两种失败，直接跳转（最后手段）
      setTimeout(() => {
        if (!document.hidden) {
          // 如果页面仍然可见，说明前两种方法可能失败了
          window.location.href = url;
        }
      }, 1000);
    },
  },
};
</script>

<style>
.page-index {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url("@/assets/bg.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  /* 移动端可以移除 fixed 背景，因为某些移动设备不支持 */
  /* background-attachment: fixed; */
  overflow: auto;
  /* 添加触摸滚动优化 */
  -webkit-overflow-scrolling: touch;
}

.content {
  /* 减少顶部内边距以适应移动端 */
  padding-top: 60px;
  text-align: center;
  /* 使用视口单位确保高度适应 */
  min-height: calc(100vh - 60px);
  /* 添加左右内边距防止内容贴边 */
  padding-left: 15px;
  padding-right: 15px;
  /* 盒子模型优化 */
  box-sizing: border-box;
}

.logo {
  /* 减小logo尺寸 */
  height: 80px;
  width: 80px;
  /* 调整上下边距 */
  margin-top: 60px;
  margin-bottom: 20px;
}

.title {
  /* 减小字体大小 */
  font-size: 22px;
  font-weight: 700;
  color: #fff;
  margin-bottom: 20px;
  /* 添加文字阴影提高可读性 */
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
}

.download-btn {
  border: none;
  /* 调整为百分比宽度 */
  width: 80%;
  max-width: 244px;
  height: 45px;
  /* 增大字体便于点击 */
  font-size: 16px;
  font-weight: 500;
  color: #b70e18;
  background: #fff;
  border-radius: 8px;
  /* 添加点击反馈 */
  transition: transform 0.1s;
  /* 增加按钮阴影 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.download-btn:active {
  transform: scale(0.98);
}

.wxtip {
  background: rgba(0, 0, 0, 0.8);
  text-align: center;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 998;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* 修改这里 - 将内容整体向上移动 */
  justify-content: flex-start;
  padding-top: 15%; /* 控制整体上移的距离，可以根据需要调整百分比 */
  box-sizing: border-box;
}

.wxtip-icon {
  width: 120px;
  height: auto;
  /* 移除原来的margin-left */
  margin: 0 0 48px 30%; /* 只保留底部margin */
  aspect-ratio: 150/220;
}

.wxtip-txt {
  color: #fff;
  font-size: 20px;
  line-height: 1.5;
  padding: 0 15px;
  max-width: 300px;
}
</style>
